import Vue from 'vue'
import Vuex from 'vuex'

//Vue中绑定Vuex
Vue.use(Vuex)

//创建Vuex对象
let store = new Vuex.Store({
    //数据存储
    state:{
        name:'张三丰',
        age:99,
        counter:1000,
        username:'',
        msg:'我是恐怖分子，我有枪，我很暴力！'
    },
    mutations:{
        //给username 赋值
        setUsername(state,name){
            state.username = name;
        },
        addCount(state,num){
            state.counter = state.counter +num ;
        }
    },
    getters:{
        changeCount(state){
            return state.counter * 2 ;
        },
        test01(state){
            let arr = ['恐怖分子','枪','暴力'];
            let s = state.msg ;
            for (let a of arr) {
                let ss = '' ;
                for (let i=0;i<a.length;i++) {
                    ss += "*";
                }
                if (s.indexOf(a) != -1) {
                    s = s.replaceAll(a,ss);
                }
            }
            return s ;
        }
    },
    //action中执行的时候，属于异步操作
    actions:{
        updateCount(context,payload){
            /*setTimeout(()=>{
                context.commit("addCount",payload);
            },2000)*/
            setInterval(()=>{
                context.commit("addCount",payload);
            },3000)
        }
    },
    modules:{
        a:{
            state:{
                city:"合肥"
            },
            mutations:{
                changeCity(state){
                    state.city = "南京";
                }
            }
        },
        b:{
            state:{
                province:'安徽省'
            },
            mutations:{
                changeProvince(state){
                    state.province = "江苏省"
                }
            }
        }
    }
})

//导出 Vuex对象
export default store ;